using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.LMZWorkSchedule;

namespace WPF_MVVM_Test.Services
{
    /// <summary>
    /// API服务类，用于处理HTTP请求
    /// </summary>
    public class ApiService
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl;

        public ApiService()
        {
            _httpClient = new HttpClient();
            _baseUrl = "http://8.140.242.140:8888"; // 根据你的API地址调整
            
            // 设置默认请求头
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
        }

        /// <summary>
        /// 获取质检方案列表
        /// </summary>
        /// <returns>质检方案列表</returns>
        public async Task<ApiResponse<List<QualityInspectionPlan>>> GetQualityInspectionPlansAsync()
        {
            try
            {
                var url = $"{_baseUrl}/api/LMZWorkSchedule/quality-inspection-plans";
                
                var response = await _httpClient.GetAsync(url);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var result = JsonSerializer.Deserialize<ApiResponse<List<QualityInspectionPlan>>>(
                        responseContent, 
                        new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
                    
                    return result ?? GetFallbackQualityInspectionPlans();
                }
                else
                {
                    // API请求失败时使用测试数据，不显示错误信息
                    return GetFallbackQualityInspectionPlans();
                }
            }
            catch (Exception ex)
            {
                // 请求异常时使用测试数据，不显示错误信息
                return GetFallbackQualityInspectionPlans();
            }
        }

        /// <summary>
        /// 获取质检方案测试数据（当API失败时使用）
        /// </summary>
        /// <returns>质检方案测试数据</returns>
        private ApiResponse<List<QualityInspectionPlan>> GetFallbackQualityInspectionPlans()
        {
            var testData = new List<QualityInspectionPlan>
            {
                new QualityInspectionPlan
                {
                    Id = "bd5e8edf-0885-3948-abcf-89bb444726c3",
                    PlanName = "功能性测试",
                    PlanCode = "ZJ1298640711432",
                    DetectionCategory = "影视用品",
                    DetectionTypes = "影视用品",
                    Status = "启用",
                    Remark = "数据库经理",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-01T08:56:48.88787"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "fe060ebc-5036-8371-885d-dcdc6a1b5207",
                    PlanName = "耐磨性测试",
                    PlanCode = "ZJ0304682479594",
                    DetectionCategory = "艺术，手工艺品及缝纫",
                    DetectionTypes = "艺术，手工艺品及缝纫",
                    Status = "启用",
                    Remark = "教授",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-01T08:56:48.887934"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "08cf5c8f-f668-459e-2c85-91900627afdd",
                    PlanName = "耐温性能测试",
                    PlanCode = "ZJ2895204338830",
                    DetectionCategory = "工具与家居装饰",
                    DetectionTypes = "工具与家居装饰",
                    Status = "启用",
                    Remark = "时装设计师",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-01T08:56:48.887935"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "dcd804ad-e8ca-0f1d-7266-0a804feba703",
                    PlanName = "耐腐蚀性测试",
                    PlanCode = "ZJ3298043597237",
                    DetectionCategory = "收藏品及美术用品",
                    DetectionTypes = "收藏品及美术用品",
                    Status = "启用",
                    Remark = "运营经理",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-02T00:50:26.873306"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "9b01f036-bdb8-899c-3ab0-ba88aad7774d",
                    PlanName = "外观质量检验",
                    PlanCode = "ZJ0217302849761",
                    DetectionCategory = "家电",
                    DetectionTypes = "家电",
                    Status = "启用",
                    Remark = "舞蹈演员",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-02T07:08:31.556505"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "cae3092d-300f-c83b-0243-246a36fc97d7",
                    PlanName = "振动测试",
                    PlanCode = "ZJ1577251555289",
                    DetectionCategory = "手工制作",
                    DetectionTypes = "手工制作",
                    Status = "启用",
                    Remark = "药剂师",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-02T07:08:31.556505"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "e0e06f63-e044-607f-0ab4-fa3a8a72b0d8",
                    PlanName = "电气性能检验",
                    PlanCode = "ZJ6480671064572",
                    DetectionCategory = "玩具与游戏",
                    DetectionTypes = "玩具与游戏",
                    Status = "启用",
                    Remark = "保险销售代理",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-02T07:08:31.556505"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "842f5b50-f13c-0f8f-2767-3c8292f9f9a1",
                    PlanName = "电气性能检验",
                    PlanCode = "ZJ3959068665781",
                    DetectionCategory = "其他",
                    DetectionTypes = "其他",
                    Status = "启用",
                    Remark = "商务记者",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-02T07:08:31.556506"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "60a95de5-445d-d1ac-f91a-e14de054bff8",
                    PlanName = "材料强度测试",
                    PlanCode = "ZJ0091553594067",
                    DetectionCategory = "乐器用品",
                    DetectionTypes = "乐器用品",
                    Status = "启用",
                    Remark = "多媒体动画师",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-02T07:08:31.556506"),
                    ExpiryTime = null
                },
                new QualityInspectionPlan
                {
                    Id = "5284fdde-51dc-7d91-8e93-ff6b502d979c",
                    PlanName = "冲击测试",
                    PlanCode = "ZJ7743980935535",
                    DetectionCategory = "收藏品及美术用品",
                    DetectionTypes = "收藏品及美术用品",
                    Status = "启用",
                    Remark = "时装设计师",
                    Version = 1,
                    VersionDescription = "质检操作添加",
                    IsCurrentVersion = true,
                    EffectiveTime = DateTime.Parse("2025-08-02T07:08:31.556506"),
                    ExpiryTime = null
                }
            };

            return new ApiResponse<List<QualityInspectionPlan>>
            {
                IsSuc = true,
                Code = 200,
                Msg = "操作成功",
                Data = testData
            };
        }

        /// <summary>
        /// 处理质检报工
        /// </summary>
        /// <param name="workReportInspectionId">报工质检ID</param>
        /// <param name="qualityInspectionPlanIds">质检方案ID数组</param>
        /// <returns>API响应结果</returns>
        public async Task<ApiResponse<ProcessQualityInspectionResponse>> ProcessQualityInspectionAsync(
            Guid workReportInspectionId, 
            string[] qualityInspectionPlanIds)
        {
            try
            {
                var url = $"{_baseUrl}/api/QualityInspectionPlanWorkReport/process-quality-inspection?workReportInspectionId={workReportInspectionId}";
                
                // 直接序列化字符串数组，不包装在对象中
                var json = JsonSerializer.Serialize(qualityInspectionPlanIds);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var result = JsonSerializer.Deserialize<ApiResponse<ProcessQualityInspectionResponse>>(
                        responseContent, 
                        new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
                    
                    return result ?? new ApiResponse<ProcessQualityInspectionResponse>
                    {
                        IsSuc = false,
                        Code = 500,
                        Msg = "响应数据解析失败"
                    };
                }
                else
                {
                    return new ApiResponse<ProcessQualityInspectionResponse>
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.ReasonPhrase}"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse<ProcessQualityInspectionResponse>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 通用GET请求方法
        /// </summary>
        /// <param name="endpoint">API端点</param>
        /// <returns>响应内容字符串</returns>
        public async Task<string> GetAsync(string endpoint)
        {
            try
            {
                var url = $"{_baseUrl}{endpoint}";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    throw new HttpRequestException($"请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }

    /// <summary>
    /// API响应基类
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    public class ApiResponse<T>
    {
        public T? Data { get; set; }
        public bool IsSuc { get; set; }
        public int Code { get; set; }
        public string Msg { get; set; } = string.Empty;
    }

    /// <summary>
    /// 质检处理响应数据
    /// </summary>
    public class ProcessQualityInspectionResponse
    {
        public string WorkReportInspectionId { get; set; } = string.Empty;
        public string Status { get; set; } = string.Empty;
        public DateTime ProcessedAt { get; set; }
        public string ProcessedBy { get; set; } = string.Empty;
        public int AddedAssociationsCount { get; set; }
        public string[] AssociationIds { get; set; } = Array.Empty<string>();
        public bool IsSuccess { get; set; }
    }
}